package top.zhouze.common.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.Arrays;

/**
 * @author 周仄
 * @since 2024/5/9 上午9:11
 */
public class PermissionUtil {
    public static final int defaultRequestCode = 10000;
    /**
     * 请求权限
     *
     * @param activity    活动
     * @param permissions 权限
     */
    public static void requestPermission(Activity activity, String... permissions) {
        requestPermission(activity,defaultRequestCode,permissions);
    }

    public static void requestPermission(Activity activity,int requestCode, String... permissions) {
        if (permissions.length != 0) {
            if (Build.VERSION.SDK_INT >= 23) {
                //判断是否拥有权限
                String[] permissionArr = Arrays.stream(permissions)
                        .filter(permission -> {
                            int nRet = ContextCompat.checkSelfPermission(activity, permission);
                            return nRet != PackageManager.PERMISSION_GRANTED;
                        }).toArray(String[]::new);

                if (permissionArr.length > 0) {
                    ActivityCompat.requestPermissions(activity, permissionArr, requestCode);
                }
            }
        }
    }

    /**
     * Android11以上在sd卡写入须要请求所有文件权限
     *
     * @param context 上下文
     */
    public static void requestAllFilesPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                context.startActivity(intent);
            }
        }
    }
}
